package com.cci.kangdao.utilTool;

import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.entity.FileEntity;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author William Du
 * @date 2020/2/6
 */
public abstract class FileUploadUtils {

    private static Logger log = Logger.getLogger(Upload_Util.class);

    public static List<FileEntity> uploadMultiFile(HttpServletRequest request, String fileBasePath) {
        List<FileEntity> fileList = new ArrayList<>();
        try {
            File dir = new File(fileBasePath);
            if(!dir.exists()){
                dir.mkdir();
            }
            long startTime = System.currentTimeMillis();
            // 将当前上下文初始化给 CommonsMultiPartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        FileEntity fileEntity = new FileEntity();
                        // 文件名
                        String name = Date_Util.GetTime(7, 0) + "_" + file.getOriginalFilename();
                        String pathName = String.format("%s/%s", fileBasePath, name);
                        // 上传
                        file.transferTo(new File(pathName));
                        // 拼装文件对象实体
                        fileEntity.setFileName(file.getOriginalFilename());
                        fileEntity.setFilePath(pathName);
                        fileList.add(fileEntity);
                    }
                }
            }
            long endTime = System.currentTimeMillis();
            log.info("上传文件到服务器成功，耗时：" + (endTime - startTime) + "ms");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return fileList;
    }

    public static List<FileEntity> uploadAzureFile(List<FileEntity> filePathList) {
        List<FileEntity> fileEntityList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(filePathList)) {
            long startTime = System.currentTimeMillis();
            String azureAccount = PropertiesUtil.getProperties("projectconfig.properties", "accountName").trim();
            String blobConnection = PropertiesUtil.getProperties("projectconfig.properties", "blobConnection").trim();
            String containerName = PropertiesUtil.getProperties("projectconfig.properties", "containerName").trim();
            for (FileEntity fileEntity : filePathList) {
                String azureFileUrl = AzureBlobTool.uploadBlob(azureAccount, blobConnection, containerName, fileEntity.getFilePath());
                if (StringUtils.isNotEmpty(azureFileUrl)) {
                    fileEntity.setFileUrl(azureFileUrl);
                    fileEntityList.add(fileEntity);
                }
            }
            long endTime = System.currentTimeMillis();
            log.info("上传文件到微软云成功，耗时：" + (endTime - startTime) + "ms");
        }
        return fileEntityList;
    }

    public static void clearFile(String filePath) {
        try {
            File clearFile = new File(filePath);
            if (clearFile.exists()) {
                FileUtils.forceDelete(clearFile);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void clearFiles(List<FileEntity> filePathList) {
        if (CollectionUtils.isNotEmpty(filePathList)) {
            for (FileEntity fileEntity : filePathList) {
                clearFile(fileEntity.getFilePath());
            }
        }
    }
}
